﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OF.Utility
{
    public static class ObjectUtility
    {

        /// <summary>
        /// 将c# DateTime时间格式转换为Unix时间戳格式
        /// </summary>
        /// <param name="time">时间</param>
        /// <returns>double</returns>
        public static int GetTimestamp(this System.DateTime time)
        {
            int intResult = 0;
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            intResult = Convert.ToInt32((time - startTime).TotalSeconds);
            return intResult;
        }

        /// <summary>
        /// 对象进行xml序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectXmlSerialization(this object obj)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                new System.Xml.Serialization.XmlSerializerFactory().CreateSerializer(obj.GetType()).Serialize(ms, obj);
                System.IO.StreamReader reader = new System.IO.StreamReader(ms);
                ms.Position = 0;//重置流位置
                return reader.ReadToEnd();
            }
        }
        /// <summary>
        /// 对象进行xml序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ObjectJSONSerialization(this object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }
    }
}
